import moment from 'moment'
import { ElMessage } from 'element-plus'
import { httpRequestLogin, httpUserInfo, changeAvatar, httpPhoneLogin } from '@/api/user.js'

const TokenKey = 'ai_teacher_student_user_token'
const expire_day = 7

export function getToken() {
  const token = window.localStorage.getItem(TokenKey)
  if (!token) {
    return ''
  }
  const tokenObject = JSON.parse(token)
  if (tokenObject && tokenObject.token && tokenObject.expire > moment.now()) {
    return tokenObject.token
  }
  removeToken()
  return ''
}

export function setToken(token) {
  window.localStorage.setItem(
    TokenKey,
    JSON.stringify({
      token: token,
      expire: expire_day * 86400000 + moment.now(),
    })
  )
}

export function removeToken() {
  window.localStorage.removeItem(TokenKey)
}

export async function requestLogin(userInfo) {
  const { username, password, category, login_type, phone_number, phone_code } = userInfo
  if (login_type === 1) {
    const response = await httpRequestLogin({
      username,
      password,
      category,
    }).catch(() => null)
    if (!response) return ''
    const { token } = response
    return token ? token : ''
  } else if (login_type === 2) {
    const response = await httpPhoneLogin({
      phone_number,
      phone_code,
      category
    }).catch(() => null)
    if (!response) return ''
    if (response.token) {
      return response.token
    } else {
      return false
    }
  }
}

export async function getUserInfo(token) {
  if (!token) {
    ElMessage.error('请登录！')
    return false
  }
  const response = await httpUserInfo()
  if (!response) return false
  const { code, name, avatar, pwd_changed, type, user_info_id, read_password } =
    response
  return {
    code: code,
    name: name,
    avatar: avatar,
    pwd_changed: pwd_changed,
    type: type,
    user_info_id: user_info_id,
    read_password: read_password,
  }
}

export async function updateUserAvatar(avatar) {
  const response = await changeAvatar(avatar)
  if (!response) return false
  return true
}
